package com.sk.waste.app.fragments

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.lc.smc.lib.views.pulllayout.SKPullRefresh
import com.lc.smc.lib.views.pulllayout.SKPullRefreshLayout
import com.sk.waste.app.R
import com.sk.waste.app.activitys.MainActivity
import com.sk.waste.app.activitys.PushActivity
import com.sk.waste.app.activitys.PushDetailActivity
import com.sk.waste.app.adapters.SpaceAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.bases.BaseFragment
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.SpaceModel
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 * 空间
 */
class SpaceFragment : BaseFragment() {

    private var ettSearch: EditText? = null
    private var bttSearch: Button? = null
    private var recyclerView: RecyclerView? = null
    private var pullRefreshLayout: SKPullRefreshLayout? = null

    private lateinit var mAdapter: SpaceAdapter
    private var merchantList = ArrayList<SpaceModel>()

    private var searchStr = ""
    private var currentPage = 1
    val userinfo = MyApplication.instance.getUserInfo()

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.fragment_space)
        super.onCreate(savedInstanceState)
    }

    override fun findView() {
        ettSearch = findViewById(R.id.view_search_text) as EditText?
        bttSearch = findViewById(R.id.view_search_butt) as Button?
        recyclerView = findViewById(R.id.fg_merchant_recyclerview) as RecyclerView?
        pullRefreshLayout = findViewById(R.id.ac_swipe_refreshLayout) as SKPullRefreshLayout?
    }

    override fun setListener() {
        pullRefreshLayout!!.onStartListener = refreshListener
        pullRefreshLayout!!.onStartListener.onStartRefresh(pullRefreshLayout)
        recyclerView!!.layoutManager = LinearLayoutManager(mContext)
        mAdapter = SpaceAdapter(requireActivity(), 0, merchantList, mOnItemClickListener)
        recyclerView!!.adapter = mAdapter

        bttSearch!!.setOnClickListener {
            merchantList.clear()
            currentPage = 1
            mAdapter.notifyDataSetChanged()
            searchStr = ettSearch!!.text.toString()
            hideKeyboard()
            getMerchantList()
        }
        ettSearch!!.setOnEditorActionListener { v, actionId, event -> // 在这里处理搜 索逻辑
            // 返回 true 表示你已经处理了这个事件
            merchantList.clear()
            currentPage = 1
            mAdapter.notifyDataSetChanged()
            searchStr = ettSearch!!.text.toString()
            hideKeyboard()
            getMerchantList()
            true
        }

        (requireActivity() as MainActivity).ttvPush.setOnClickListener {
            val intent = Intent(mContext, PushActivity::class.java)
            pushActivityResultLauncher.launch(intent)
        }

    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val position = args[0] as Int
            val intent = Intent(mContext, PushDetailActivity::class.java)
            intent.putExtra("extral_pushid", merchantList[position].id)
            startActivity(intent)
        }

    }

    private val refreshListener = object : SKPullRefresh.OnStartListener {
        override fun onStartRefresh(p0: SKPullRefresh?) {
            currentPage = 1
            getMerchantList()
        }

        override fun onStartLoadmore(p0: SKPullRefresh?) {
            if (userinfo!!.isVip()) {
                currentPage++
                getMerchantList()
            } else {
                currentPage = 1
                pullRefreshLayout!!.loadmoreSuccess()
            }
        }
    }

    /**
     *  @time 2024/5/7  11:29
     *  @desc 空间列表
     *  @param url
     */
    private fun getMerchantList() {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_SPACE_LIST
        val token = LCSPUtil[mContext!!, AppConfig.SP_ACCESS_TOKEN]
        val params = JSONObject()
        params.put("pageSize", AppConfig.PAGE_SIZE)
        params.put("pageNo", currentPage)
        params.put("infoContent", searchStr)
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                freshOrLoadFaild()
                LCBaseUtil.showToast(context, "获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val code = jsonObject.getInt("code")
                    if (currentPage == 1) {
                        merchantList.clear()
                    }
                    if (success) {
                        val data = jsonObject.getJSONObject("data")
                        val rows = data.getJSONArray("rows")
                        activity!!.runOnUiThread {
                            if (rows.length() == 0) {
                                showToastLong("暂无数据...")
                            }
                            fresOrLoadSuccess(rows.length())
                            for (index in 0 until rows.length()) {
                                val item = SpaceModel().apply { getModelInfo(rows.getJSONObject(index)) }
                                val imgArray = rows.getJSONObject(index).getJSONArray("imageList")
                                for (i in 0 until imgArray.length()) {
                                    item.imgList.add(imgArray.getJSONObject(i).getString("imageUrl"))
                                }
                                merchantList.add(item)
                            }
                            mAdapter.notifyDataSetChanged()
                        }
                        LCLogger.d(TAG, "获取成功！,返回信息：$jsonObject")
                    } else {
                        freshOrLoadFaild()
                        LCBaseUtil.showToast(context, "获取失败，$msg")
                    }
                } catch (e: Exception) {
                    freshOrLoadFaild()
                    LCBaseUtil.showToast(context, "获取失败，" + e.message)
                    Log.e("LCLOG_ERROR", e.toString())
                }
            }
        })
    }

//    private fun judgeVip()
//    {
//        val userinfo = MyApplication.instance.getUserInfo()
//        if (userinfo?.isVip() == true) {
//            pullRefreshLayout!!.isLoadmoreable = true;
//        } else {
//            pullRefreshLayout!!.isLoadmoreable = false;
//        }
//    }

    private fun fresOrLoadSuccess(rows: Int) {
        if (1 == currentPage) { // 刷新
            pullRefreshLayout!!.refreshSuccess()
            merchantList.clear()
        } else {
            pullRefreshLayout!!.loadmoreSuccess()
        }
        if (rows == AppConfig.PAGE_SIZE) {
            pullRefreshLayout!!.isLoadmoreable = true
        } else {
            pullRefreshLayout!!.isLoadmoreable = false
        }
    }

    private fun freshOrLoadFaild() {
        activity?.runOnUiThread {
            if (currentPage == 1) {
                //            pullRefreshLayout.stopRefresh()
                //                pullRefreshLayout.refreshSuccess();
                pullRefreshLayout!!.refreshFailed();
            } else {
                //                pullRefreshLayout.loadmoreSuccess()
                pullRefreshLayout!!.loadmoreFailed()
            }
        }
    }

    private val pushActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data = result.data
            // 处理返回的数据
            if (data?.getBooleanExtra("push_reust", false) == true) {
                merchantList.clear()
                currentPage = 1
                getMerchantList()
            }
        }
    }

}